﻿using Grpc.Net.Client;
using GrpcBase;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using SX.Core;
using SX.Core.Attributes;
using SX.Core.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SX.ProductService.API.Base
{

    public class PermissionHandler : IPermissionHandler
    {
        private readonly ILoginInfo _loginInfo;
        public PermissionHandler( ILoginInfo loginInfo)
        {
            _loginInfo = loginInfo;
        }
        public async Task<bool> ValidateAsync(IDictionary<string, string> routeValues, string httpMethod)
        {
            var permissions = new List<string>();
            //方式一：调用Base服务API查询当前登录用户所有权限 
            //HttpHelper.HttpGetOutCode()
            //方式二：Grpc
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            var channel = GrpcChannel.ForAddress("http://localhost:9001");
            var client = new GetPermissions.GetPermissionsClient(channel);
            var reply =await client.GetPermissionsByUIdAsync(
                new GetPermissionsRequest { Userid = _loginInfo.UserId });
            permissions = JsonHelper.DeserializeObject<List<string>>(reply.Permissions);
            var area = routeValues["area"];
            var controller = routeValues["controller"];
            var action = routeValues["action"];
            return permissions.Any(m => m.EqualsIgnoreCase($"{area}_{controller}_{action}"));
        }
    }


    /// <summary>
    /// 自定义权限验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public class PermissionAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
    {
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            //AllowAnonymous
            if (context.ActionDescriptor.EndpointMetadata.Any(m => m.GetType() == typeof(AllowAnonymousAttribute)))
                return;

            //登录验证
            var login = context.HttpContext.RequestServices.GetService<ILoginInfo>();
            if (login == null || !(login?.UserId.Length > 0))
            {
                context.Result = new ChallengeResult();
                return;
            }

            //排除通用接口 登录就可以访问的接口 不需要授权
            if (context.ActionDescriptor.EndpointMetadata.Any(m => m.GetType() == typeof(CommonAttribute)))
                return;

            //超级管理员不进行权限验证

            //权限验证
            var httpMethod = context.HttpContext.Request.Method;
            var handler = context.HttpContext.RequestServices.GetService<IPermissionHandler>();

            if (!await handler.ValidateAsync(context.ActionDescriptor.RouteValues, httpMethod))
            {
                //无权限
                context.Result = new ForbidResult();
            }

        }
    }

}
